package xin.huangyan.accessibilityapp.utils;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileWriter;

public class HLog {
    public static String TAG = "HLOG-";
    public static void i(String msg){
        StackTraceElement[] s = new Exception().getStackTrace();
        Log.i(TAG + s[1].getClassName() + "-" + s[1].getLineNumber(), msg);
    }
    public static void e(String msg){
        StackTraceElement[] s = new Exception().getStackTrace();
        Log.e(TAG + s[1].getClassName() + "-" + s[1].getLineNumber(), msg);
    }

    private static String logPath = null;
    public static String getLogPath(Context context) {
        if (!TextUtils.isEmpty(logPath)) {
            return logPath;
        }
        logPath = context.getCacheDir().getAbsolutePath()
                + File.separator + "CameraApp";
        File filePath = new File(logPath);
        String result = "";
        if (!filePath.exists()) {
            result = ""+filePath.mkdirs();
        }
        i("result:" + result);
        return logPath;
    }

    /**
     * 写日志到文件
     * @param msg
     * @param fileName
     */
    public static boolean writeLog(Context context, String msg, String fileName, boolean append){
        FileWriter fw = null;
        boolean result = false;
        try {
            String filePath = getLogPath(context) + File.separator + fileName;
            fw = new FileWriter(filePath, append);
            fw.write(msg + "\n");
            result = true;
        } catch (Exception e) {
            i("write log exception:" + e);
        }finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (Exception e) {

                }
            }
        }
        return result;
    }
}
